const path = require('path')
const fs = require('fs')
const express = require('express')
const ReactSSR = require('react-dom/server')
const port = 8080
const app = express()

import React from 'react';
import App from '../pages/app';
import { StaticRouter } from 'react-router';
import { createStore } from 'redux'
import { Provider } from 'react-redux'

let BootStart = (root) => {

    const reducer = (state = {}, action) => {
        const target = Object.assign({}, state, action.state)
        switch (action.type) {
            default:
                return target
        }
    }

    const store = createStore(reducer)

    const unsub = store.subscribe(() => {
        let state = store.getState()
    })

    const serverEntry = (url) => {
        return (
            <Provider store={store}>
                <StaticRouter url={url} >
                    <App />
                </StaticRouter>
            </Provider>
        )
    }

    //跨域配置
    app.all('*', function (req, res, next) {
        res.header('Access-Control-Allow-Origin', '*')
        res.header('Access-Control-Allow-Headers', 'Content-Type')
        res.header('Access-Control-Allow-Methods', '*')
        next()
    });

    app.get(`/*`, (req, res, next) => {
        if (req.url.endsWith('.js')
            || req.url.endsWith('.jpg')
            || req.url.endsWith('.png')
            || req.url.endsWith('.gif')
            || req.url.endsWith('.css')
            || req.url.endsWith(".mp3")
            || req.url.endsWith(".html")
            || req.url.match(/.*\.[mM][dD](\?[^\?]*)?/)) {
            next()
        } else {
            let filePath = path.join(root, 'dist', 'index.html')
            fs.readFile(filePath, 'utf8', (err, indexContent) => {
                let render = new Promise((resolve, reject) => {
                    const content = ReactSSR.renderToString(serverEntry(req.url))
                    const html = indexContent.replace('<!--content-->', content)
                    resolve(html)
                })
                render.then((html) => {
                    let text = html.replace('<!--INIT_STATE-->',JSON.stringify(store.getState()))
                    res.send(text)
                })
            })
        }
    })

    app.get('*.html', (req, res, next) => {
        res.download(path.join(root, 'dist', req.url))
    })

    app.get(/.*\.[mM][dD](\?[^\?]*)?/, (req, res, next) => {
        let idx = req.url.indexOf("?")
        let file
        if (idx < 0) {
            file = path.join(root, 'dist', req.url)
        } else {
            file = path.join(root, 'dist', req.url.substr(0, idx))
        }
        res.download(file)
    })

    app.get(`*.js`, (req, res, next) => {
        res.download(path.join(root, 'dist', req.url))
    })

    app.get(`*.mp3`, (req, res, ne) => {
        res.download(path.join(root, 'dist', req.url))
    })

    app.get(`*.jpg`, (req, res, next) => {
        res.download(path.join(root, 'dist', req.url))
    })

    app.get(`*.png`, (req, res, next) => {
        res.download(path.join(root, 'dist', req.url))
    })

    app.get(`*.gif`, (req, res, next) => {
        res.download(path.join(root, 'dist', req.url))
    })

    app.get(`*.css`, (req, res, next) => {
        res.download(path.join(root, 'dist', req.url))
    })

    app.listen(port, function () {
        console.log(`成功的开启服务，端口号：${port}`)
    })
}

export default BootStart